package com.sky.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.domain.WxUser;
import com.sky.dto.UserPwdUpdateDto;
import com.sky.dto.WxUserDto;
import com.sky.dto.WxUserLoginDto;
import com.sky.mapper.WxUserMapper;
import com.sky.service.WxUserService;
import com.sky.utils.AppMd5Utils;
import com.sky.vo.DataGridView;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author majinan
 */
@Service
public class WxUserServiceImpl implements WxUserService {

    @Autowired
    private WxUserMapper userMapper;

    @Override
    public WxUser queryUserByPhone(String phone) {
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq(WxUser.COL_PHONE, phone);
        return this.userMapper.selectOne(qw);
    }

    @Override
    public WxUser getOne(Long userId) {
        return this.userMapper.selectById(userId);
    }

//    @Override
//    public DataGridView listUserForPage(WxUserDto userDto) {
//        Page<WxUser> page = new Page<>(userDto.getPageNum(), userDto.getPageSize());
//        QueryWrapper<WxUser> qw = new QueryWrapper<>();
//        qw.like(StringUtils.isNotBlank(userDto.getUserName()), WxUser.COL_USER_NAME, userDto.getUserName());
//        qw.like(StringUtils.isNotBlank(userDto.getPhone()), WxUser.COL_PHONE, userDto.getPhone());
//        qw.orderByAsc(WxUser.COL_USER_ID); this.userMapper.selectPage(page,qw);
//        return new DataGridView(page.getTotal(), page.getRecords());
//    }

    @Override
    public int addUser(WxUserDto userDto) {
        WxUser temp = queryUserByPhone(userDto.getPhone());
        if (temp != null) {
            return 0;
        }
        WxUser user = new WxUser();
        BeanUtil.copyProperties(userDto,user);
        // 设置密码（默认手机号后6位）
        String defaultPwd = user.getPhone().substring(5);
        if (StringUtils.isNotEmpty(userDto.getPwd())){
            defaultPwd = userDto.getPwd();
        }
        user.setSalt(AppMd5Utils.createSalt());
        user.setPwd(AppMd5Utils.md5(defaultPwd, user.getSalt(),2));
        return this.userMapper.insert(user);
    }

    @Override
    public int updateUser(WxUserDto userDto) {
        WxUser user = this.userMapper.selectById(userDto.getId());
        if(null == user)
            return 0;
        String pwd = user.getPwd();//原密码
        BeanUtil.copyProperties(userDto,user);
        if (StringUtils.isEmpty(userDto.getPwd())){
            user.setPwd(pwd);
        }else {
            user.setSalt(AppMd5Utils.createSalt());
            user.setPwd(AppMd5Utils.md5(userDto.getPwd(), user.getSalt(),2));
        }
        return this.userMapper.updateById(user);
    }

    @Override
    public int resetPwd(Long[] userIds) {
        int res = 0;

        for(Long userId : userIds) {
            WxUser user = this.userMapper.selectById(userId);
            String defaultPwd;
            defaultPwd = user.getPhone().substring(5);
            user.setSalt(AppMd5Utils.createSalt());
            user.setPwd(AppMd5Utils.md5(defaultPwd, user.getSalt(), 2));
            res += this.userMapper.updateById(user);
        }

        return res == userIds.length ? 1 : 0;
    }

    @Override
    public int updatePwd(UserPwdUpdateDto dto) {
        if (!dto.getNewPwd().equals(dto.getConfirmPwd())){
            throw new RuntimeException("两次密码不一致");
        }
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq(WxUser.COL_USER_NAME, dto.getUserName());
        List<WxUser> users = this.userMapper.selectList(qw);
        if (CollectionUtils.isEmpty(users)){
            throw new RuntimeException("用户不存在");
        }
        WxUser user = users.get(0);
        String pwd = AppMd5Utils.md5(dto.getOriginalPwd(), user.getSalt(), 2);
        if (!pwd.equals(user.getPwd())){
            throw new RuntimeException("原密码不正确");
        }
        String newPwd = AppMd5Utils.md5(dto.getNewPwd(), user.getSalt(), 2);
        user.setPwd(newPwd);
        return this.userMapper.updateById(user);
    }

    @Override
    public List<WxUserDto> selectAllUser() {
        return null;
    }

    @Override
    public WxUser login(WxUserLoginDto dto) {
        WxUser temp = queryUserByName(dto.getUserName());
        if (temp == null) {
            return null;
        }
        String passWord = AppMd5Utils.md5(dto.getPwd(), temp.getSalt(), 2);
        if (passWord.equals(temp.getPwd())){
            return temp;
        }

        return null;
    }

    public WxUser queryUserByName(String userName) {
        QueryWrapper<WxUser> qw = new QueryWrapper<>();
        qw.eq(WxUser.COL_USER_NAME, userName);
        return this.userMapper.selectOne(qw);
    }
}
